MacroScript ExportMesh category:"Fili" tooltip:"Exports binary data to a 3DB file" icon:#("Maxscript",3)
(
	persistent global lastPathSave
	if lastPathSave == undefined then 
	(
		lastPathSave = ""
	)
	
	--object filter
	fn GetGeometry o = (Superclassof o == Geometryclass and classof o != TargetObject )
	obj = pickobject filter:GetGeometry

	if isValidNode obj then
	(
		tmesh = snapshotAsMesh obj
		
		out_name = GetSaveFileName \
			caption: "Select path for exported object" \
			types: "3D BinObjects (*.3DB)|*.3db|All Files (*.*)|*.*" \
			filename: lastPathSave

		if out_name != undefined then		
		(
			lastPathSave = out_name
			--open file in binary write mode
			out_binStream = fopen out_name "wb"

			num_verts = tmesh.numverts
			num_tverts = tmesh.numtverts
			num_faces = tmesh.numfaces

			--write identifier 3DBO
			writeLong out_binStream 0x4F424433
			
			--write file version
			writeByte out_binStream 0x01
			
			--write numbers :P
			writeLong out_binStream num_verts
			writeLong out_binStream num_tverts
			writeLong out_binStream num_faces
			
			--write padding bytes up to header size (32 bytes)
			for i = 18 to 32 do
				writeByte out_binStream 0x00
				
			--write vertex coordinates
			for i = 1 to num_verts do
			(
				tmp = (getVert tmesh i) - obj.pos
				
				writeFloat out_binStream tmp.x
				writeFloat out_binStream tmp.y
				writeFloat out_binStream tmp.z
			)
			
			--write texture coordinates
			for i = 1 to num_tverts do
			(
				tmp = getTVert tmesh i
				
				writeFloat out_binStream tmp.x
				writeFloat out_binStream tmp.y
			)
			
			--write face data
			for i = 1 to num_faces do
			(
				facev = getFace tmesh i
				facetv = getTVFace tmesh i
				facen = meshop.getFaceRNormals tmesh i
				
				--vertex index
				v = (facev.x - 1) as integer
				writeLong out_binStream v
				v = (facev.y - 1) as integer
				writeLong out_binStream v
				v = (facev.z - 1) as integer
				writeLong out_binStream v
				
				--tvertex index
				v = (facetv.x - 1) as integer
				writeLong out_binStream v
				v = (facetv.y - 1) as integer
				writeLong out_binStream v
				v = (facetv.z - 1) as integer
				writeLong out_binStream v
				
				--normals
				for j = 1 to 3 do
				(
					writeFloat out_binStream facen[j].x
					writeFloat out_binStream facen[j].y
					writeFloat out_binStream facen[j].z
				)

				--smooth groups				
				sgroup = getFaceSmoothGroup tmesh i
				writeLong out_binStream sgroup
				
				--other flags
				flags = 0
				
				if (getEdgeVis tmesh i 1) then flags = bit.or flags 0x01
				if (getEdgeVis tmesh i 2) then flags = bit.or flags 0x02
				if (getEdgeVis tmesh i 3) then flags = bit.or flags 0x04
					
				writeLong out_binStream flags
			)
			
			--everything ok, close the file
			FClose out_binStream
			
			messageBox ("Mesh data exported successfully to:\n"+out_name) title:"Success"
		)
	)
)